<?php

namespace control;
/*
*题库管理类
*/

use JetBrains\PhpStorm\NoReturn;
use JetBrains\PhpStorm\Pure;

class topicLibraryClass extends adIndexClass
{
    private const page    = 'topicLibrary';
    private const table   = 'topic_library';
    private const tableMx = 'topic_library_detail';
    private const title   = '题库管理';
    public array $itemWord = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'];

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('topic.table.orderNo')      => text(array("name" => "orderNo")),
                    L('topic.table.topicName')    => text(array("name" => "name")),
                    L('department.table.creator') => selectMultiple(array("name" => "stid", "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid', 'class' => 'width200')),
                ],
                [
                    L('department.table.creatTime') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    L('trainingPlan.table.state')   => select(array("name" => "state", "option" => ['启用' => L('topic.table.enable'), '停用' => L('topic.table.unenable')])),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $url  = root . "control/adIndex.html?cla=" . self::page;
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>" . L('recruitment.table.add') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('recruitment.table.del') . "</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'启用'})\" class='spanButton'>" . L('topic.table.enable') . "</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'停用'})\" class='spanButton'>" . L('topic.table.unenable') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo' => [
                        'name'  => L('topic.table.orderNo'),
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'name'    => [
                        'name'  => L('topic.table.topicName'),
                        'width' => 300,
                    ],
                    'type'    => [
                        'name'  => L('topic.table.topicType'),
                        'width' => 230,
                    ],
                    'state'   => [
                        'name'  => L('trainingPlan.table.state'),
                        'width' => 230,
                    ],
                    'creator' => [
                        'name'  => L('department.table.creator'),
                        'width' => 230,
                    ],
                    'time'    => [
                        'name'  => L('department.table.creatTime'),
                        'width' => 250,
                        'sort'  => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
            "name"    => $this->post('name'),//计划名称
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "stid"  => $this->post('stid'),//申请人
        );
        $and   = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate   = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('topic.table.topicInfo') . "", "click" => "newIframe('" . L('topic.table.topicInfo') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "creator":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton, "width" => 120),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId     = $this->get('templateId');
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = L('topic.table.edit_permission');
        } else {
            $exampleData[] = ['单选题', '1+1=？', '1；4；3；2', '4', 2];
            $exampleData[] = ['多选题', '中国的直辖市有以下哪些？', '重庆市；上海市；北京市；天津市', '1；2；3；4', 4];
            $exampleData[] = ['判断题', '重庆市是否是直辖市？', '是；否', '1', 2];
            $excel         = $this->excelHead();
            $fileName      = '题目导入模板-' . importTemplateClass::getName($templateId) . '.xlsx';
            $filePath      = $excel->fileName($fileName, 'sheet1');
            $format        = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']) {
                    $backgroundStyle = null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])) {
                        //必填项判断
                        $backgroundStyle = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'], '', $backgroundStyle);
                    foreach ($exampleData as $y => $example) {
                        $exampleVal = match ($array['columnName']){
                            '试题类型'=>$example[0],
                            '题干'=>$example[1],
                            '选项'=>$example[2],
                            '正确答案'=>$example[3],
                            '分值'=>$example[4],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('topic.table.topic_template'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath, $fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 格式化选项
     */
    public static function formatItem($item): array
    {
        if (empty($item)) {
            return [];
        }
        return array_filter(explode('；', $item));
    }

    /**
     * 格式化答案
     * @param $item
     * @param $index
     * @param bool $isMultiple
     * @return array
     */
    public static function formatAnswer($item, $index, $isMultiple = false): array
    {
        if ($isMultiple) {
            $answer     = [];
            $chooseItem = self::formatItem($item);
            $indexArr   = explode('；', $index);
            foreach ($chooseItem as $i => $value) {
                if (in_array($i + 1, $indexArr)) {
                    $answer[] = $i;
                }
            }
            return $answer;
        } else {
            $chooseItem = self::formatItem($item);
            $index      = $index - 1;//答案选项下标 这里是以位置为准，所以在数组中要减1
            return isset($chooseItem[$index]) ? [$index] : [];
        }
    }

    /*数据导入分析*/
    public function importData()
    {
        $id             = static::rGet(self::$stid . self::page . 'Id');//题库ID
        $templateId     = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = L('topic.table.edit_permission');
        } else {
            $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value) {
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data      = $this->importHead(format: $fomatArray);
            $x         = 0;
            $text      = '';
            $headArray = [];
            $row_list  = 0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i == 0) {
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index => $headName) {
                        $cell[$headName] = $rowData[$index] ?? '';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value) {
                        $cell[$value['columnName']] = $cell[$value['columnName']] ?? '';
                    }
                    switch ($cell['试题类型']) {
                        case '单选题':
                            $field      = [
                                'id'        => suiji(),
                                'topicType' => '单选题',
                                'title'     => $cell['题干'],
                                'score'     => $cell['分值'],
                                'item'      => $cell['选项'] ? json_encode(self::formatItem($cell['选项']), 320) : [],
                                'answer'    => json_encode(self::formatAnswer($cell['选项'], $cell['正确答案']), 320),
                                'orderId'   => $id,
                                'state'     => '启用',
                                'stid'      => $this->control['stid'],
                                'time'      => $this->time,
                            ];
                            $annotation = [
                                'title'  => L('topic.table.stem'),
                                'item'   => L('topic.table.option'),
                                'answer' => L('topic.table.answer'),
                            ];
                            $rules      = [
                                'title'  => 'required',
                                'item'   => 'required',
                                'answer' => 'required',
                            ];
                            break;
                        case '多选题':
                            $field      = [
                                'id'        => suiji(),
                                'orderId'   => $id,
                                'state'     => '启用',
                                'stid'      => $this->control['stid'],
                                'time'      => $this->time,
                                'topicType' => '多选题',
                                'title'     => $cell['题干'],
                                'score'     => $cell['分值'],
                                'item'      => $cell['选项'] ? json_encode(self::formatItem($cell['选项']), 320) : [],
                                'answer'    => json_encode(self::formatAnswer($cell['选项'], $cell['正确答案'], true), 320),
                            ];
                            $annotation = [
                                'title'  => L('topic.table.stem'),
                                'item'   => L('topic.table.option'),
                                'answer' => L('topic.table.answer'),
                            ];
                            $rules      = [
                                'title'  => 'required',
                                'item'   => 'required',
                                'answer' => 'required',
                            ];
                            break;
                        case '判断题':
                            $field      = [
                                'id'        => suiji(),
                                'orderId'   => $id,
                                'state'     => '启用',
                                'stid'      => $this->control['stid'],
                                'time'      => $this->time,
                                'topicType' => '判断题',
                                'title'     => $cell['题干'],
                                'score'     => $cell['分值'],
                                'item'      => $cell['选项'] ? json_encode(self::formatItem($cell['选项']), 320) : [],
                                'answer'    => json_encode(self::formatAnswer($cell['选项'], $cell['正确答案']), 320),
                            ];
                            $annotation = [
                                'title'   => L('topic.table.stem'),
                                'item'    => L('topic.table.option'),
                                'answer'  => L('topic.table.answer'),
                                'orderId' => L('topic.table.topicId'),
                            ];
                            $rules      = [
                                'title'   => 'required',
                                'item'    => 'required',
                                'answer'  => 'required',
                                'orderId' => 'required',
                            ];
                            break;
                    }
                    if (isset($field) && isset($annotation) && isset($rules)) {
                        $line = str_replace(['{{i}}'], [$row_list], L('job.other.line'));
                        // 校验是否符合规则
                        $vt     = new \verify();
                        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                        if ($result === false) {
                            $text .= $line . "：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                        } else {
                            $warn = static::insert(["table" => self::table . "_detail", "field" => $field]);
                            if (in_array($warn, ["新增成功", "更新成功"])) {
                                $x++;
                                $text .= $line . "：" . L('job.other.import_success') . "<br>";
                            } else {
                                $text .= $line . "：" . L('job.other.import_failed') . $warn . "<br>";
                            }
                        }
                    }
                }
            }
            $total        = count($data) - 1;
            $json['data'] = [
                'text'  => $text,
                'title' => "您导入了{$total}条数据，成功{$x}条，失败" . ($total - $x) . "条",
            ];
            $text         = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $warn             = str_replace(['{{x}}'], [$x], L('job.other.import_warn'));
            $_SESSION['warn'] = $warn;
            $json['warn']     = 1;
        }
        return json_encode($json, 320);
    }


    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id   = $this->post('id');
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('topic.table.topicType') . "：" => select(array("name" => "type", "value" => $info['type'], "title" => L('topic.table.topicType'), "option" => explode('，', para('topicLibraryOption')))),
                    must . L('topic.table.topicName') . "：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                ],
                [
                    L('recruitment.table.text') . "：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 250, "html" => $html));
    }

    public function editEdit()
    {
        $id         = $this->post('id') ?: self::getId();
        $field      = [
            'name'       => $this->post('name'),
            'type'       => $this->post('type'),
            'text'       => $this->post('text'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'name' => L('topic.table.topicName'),
            'type' => L('topic.table.topicType'),
        ];
        $rules      = [
            'name' => 'required',
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('topic.table.edit_permission');
        } else {
            $where = " id = '$id' ";
            $info  = query(self::table, $where);
            if (!$info['id']) {
                $userNo       = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'T',
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => '',
                ], $field);
                $field        = array_merge($field, [
                    'id'      => $id,
                    'orderNo' => $userNo,
                    'stid'    => $this->control['stid'],
                    'state'   => '启用',
                    'time'    => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['name'], $id], L('topic.table.edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('topic.table.find_none_info');
        } else {
            //菜单
            $data     = array(
                "id" => $info['id'],
            );
            $mxButton = '';//招聘目标按钮
            $button   = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                //按钮
                $button[] = [
                    "name"  => L('recruitment.table.edit'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];

                $mxButton = "<span class='smallButton' onclick=\"layer('" . self::page . "','addSingle',{mainId:'" . $info['id'] . "',id:'" . suiji() . "'})\">" . L('topic.table.single_new') . "</span>
                            <span class='smallButton' onclick=\"layer('" . self::page . "','addMultiple',{mainId:'" . $info['id'] . "',id:'" . suiji() . "'})\">" . L('topic.table.multiple_new') . "</span>
                            <span class='smallButton' onclick=\"layer('" . self::page . "','addJudgment',{mainId:'" . $info['id'] . "',id:'" . suiji() . "'})\">" . L('topic.table.judge_new') . "</span>
                            <span class='smallButton' onclick=\"layer('" . self::page . "','addMainTopic',{mainId:'" . $info['id'] . "',id:'" . suiji() . "'})\">" . L('topic.table.subjective_new') . "</span>
                            <span class='smallButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',act:'delMx'})\">" . L('recruitment.table.del') . "</span>
                            <span class='smallButton' onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'启用',classify:'topic'})\">" . L('topic.table.enable') . "</span>
                            <span class='smallButton' onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'停用',classify:'topic'})\">" . L('topic.table.unenable') . "</span>";
            }
            if ($this->power(self::page, 'del')) {
                $button[] = [
                    "name" => L('recruitment.table.del'),
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "import")) {
                static::rSet(self::$stid . self::page . 'Id', $info['id']);
                $mxButton .= "<span class='smallButton' onclick=\"layer('importTemplate','importFrame',{cla:'" . self::page . "'})\">导入</span>\n";
            }
            if ($this->power(self::page, "export")) {
                $mxButton .= "<span class='smallButton' onclick=\"layer('importTemplate','exportFrame',{cla:'" . self::page . "',checkbox:'mxId[]'})\">导出</span>";
            }
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time desc"));
            static::rSet(self::$stid . self::page . 'Sql', $result['sql']);
            $checkAll = $this->checkAll("detailForm", "mxId");
            $tr[]     = [$checkAll, L('topic.table.questionsType'), L('topic.table.stem'), L('topic.table.option'), L('topic.table.answer'), L('topic.table.score'), L('trainingPlan.table.state')];
            foreach ($result['array'] as $array) {
                $frame = match ($array['topicType']) {
                    '单选题' => "layer('" . self::page . "','addSingle',{mainId:'" . $info['id'] . "',id:'" . $array['id'] . "'})",
                    '多选题' => "layer('" . self::page . "','addMultiple',{mainId:'" . $info['id'] . "',id:'" . $array['id'] . "'})",
                    '判断题' => "layer('" . self::page . "','addJudgment',{mainId:'" . $info['id'] . "',id:'" . $array['id'] . "'})",
                    '主观题' => "layer('" . self::page . "','addMainTopic',{mainId:'" . $info['id'] . "',id:'" . $array['id'] . "'})",
                    default => '',
                };
                //列表控件
                $dominate   = array(
                    "box"  => array("name" => "mxId", "value" => $array['id']),
                    'edit' => array('title' => L('staffProfiles.button.edit'), 'click' => $frame)
                );
                $res        = $this->showItemAndAnswer($array);
                $itemText   = $res['itemText'];
                $answerText = $res['answerText'];
                $tr[]       = [$this->dominate($dominate), $array['topicType'], html_entity_decode($array['title'], ENT_QUOTES), $itemText, $answerText, $array['score'], $array['state']];
            }

            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html']   = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        L('topic.table.orderNo')   => $info['orderNo'],
                        L('topic.table.topicName') => $info['name'],
                        L('topic.table.topicType') => $info['type'],
                        L('department.table.creator')   => self::findStaff($info['stid']),
                    ),
                    array(
                        L('department.table.creatTime') => $info['time'],
                        L('trainingPlan.table.state')   => $info['state'],
                    ),
                    array(
                        L('staffProfiles.table.text') => $info['text'],
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => L('topic.table.questions'),
                'button' => $mxButton,
                'html' => "
                <div class='purchaseMx'>
                    <form name='detailForm'>" . hidden(array('name' => 'id', 'value' => $info['id'])) . $this->listTable(array('tr' => $tr, 'showSort' => true)) . "</form>
                </div>",
            ]);

            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId     = $this->get('templateId');
        $checkedId      = $this->get('checkedId') ? explode(',', $this->get('checkedId')) : [];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '您还没有导出的权限';
        } else {
            $info = query(self::table, "id = '" . static::rGet(self::$stid . self::page . 'Id') . "'");
            $data = [];

            $title = [];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']) {
                    $title[] = $array['aliasName'];
                }
            }
            if (!self::is_null_array($checkedId)) {
                $result = find(array(
                    "table" => self::tableMx,
                    "where" => "id in ('" . implode("','", $checkedId) . "') and orderId = '$info[id]' order by time desc",
                ))['array'];
            } else {
                $sql    = static::rGet(self::$stid . self::page . 'Sql');
                $result = sqlFind($sql);
            }
            foreach ($result as $array) {
                $column    = [];
                $answerArr = (array)json_decode($array['answer'], true);
                $answer    = [];
                foreach ($answerArr as $v) {
                    $answer[] = $v + 1;
                }
                foreach ($tempFieldAll as $templateField) {
                    if ($templateField['display']) {
                        $column[] = match ($templateField['columnName']) {
                            '试题类型' => $array['topicType'],
                            '题干' => $array['title'],
                            '选项' => implode('；', (array)json_decode(html_entity_decode($array['item'], ENT_QUOTES), true)),
                            '正确答案' => implode('；', $answer),
                            '分值' => $array['score'],
                            default => '',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $info['name']], L('topic.table.topic_export_text'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, str_replace(['{{name}}'], [$info['name']], L('topic.table.topic_export_name')) . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /**
     * 显示选项和答案
     * @param $array
     * @return string[]
     */
    public function showItemAndAnswer($array): array
    {
        $itemText = $answerText = '';
        $itemArr  = json_decode($array['item'], true);
        $answer   = json_decode($array['answer'], true);
        if (in_array($array['topicType'], ['单选题', '多选题', '判断题'])) {
            foreach ($itemArr as $k => $val) {
                $itemText .= $this->itemWord[$k] . "." . $val . '；';
                if ($array['topicType'] == '单选题' && $answer[0] == $k) {
                    $answerText .= $this->itemWord[$k] . '.' . $val;
                } elseif ($array['topicType'] == '多选题' && in_array($k, $answer)) {
                    $answerText .= $this->itemWord[$k] . '.' . $val . '；';
                } elseif ($array['topicType'] == '判断题' && $answer[0] == $k) {
                    $answerText .= $this->itemWord[$k] . '.' . $val;
                }
            }
        } else {
            $answerText = $answer[0] ?? '';
        }

        return ['itemText' => $itemText, 'answerText' => $answerText];
    }

    /**
     * 新增主观题
     */
    public function addMainTopic(): bool|string
    {
        $mx     = query(self::tableMx, " id = '{$this->post('id')}'");
        $answer = json_decode($mx['answer'], true);
        //生成表单
        $data['html'] = $this->layerEdit(array("table"  => array(
            array(
                L('topic.table.questionsType') . "：" => L('topic.table.subjective_choice'),
            ),
            array(
                L('topic.table.score') . "：" => text(array('name' => 'score', 'class' => 'text', 'value' => $mx['score']))
            ),
            array(
                must . L('topic.table.stem') . "：" => textarea(array('name' => 'title', 'class' => 'textarea', 'value' => $mx['title']))
            ),
            array(
                must . L('topic.table.answer') . "：" => textarea(array('name' => 'answer', 'class' => 'textarea', 'value' => $answer[0] ?? ''))
            )
        ),
                                               'hidden' => hidden(array('name' => 'mainId', 'value' => $this->post('mainId'))) . hidden(array('name' => 'source', 'value' => $this->post('source'))) . hidden(array('name' => 'id', 'value' => $this->post('id'))),
        ));
        //返回
        return $this->layer(array(
            "title" => L('topic.table.subjective_choice'),
            "height" => 350,
            "width" => 800,
            "html" => $data['html'],
            'button' => '<button class="button" onclick="subForm(\'' . self::page . 'AddMainTopicForm\',root+\'control/adIndex.html?cla=' . self::page . '&fun=addMainTopicEdit\')">' . L('staffProfiles.table.save') . '</button>'
        ));

    }

    /**
     * 主观题编辑
     * @return bool|string
     */
    public function addMainTopicEdit()
    {
        $id         = $this->post('id') ?: self::getId();
        $field      = [
            'topicType' => '主观题',
            'item'      => "[]",
            'title'     => $this->post('title'),
            'score'     => $this->post('score'),
            'answer'    => json_encode([$this->post('answer')], 320),
        ];
        $annotation = [
            'title'  => L('topic.table.stem'),
            'answer' => L('topic.table.answer'),
        ];
        $rules      = [
            'title'  => 'required',
            'answer' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        $info   = query(self::table, " id = '" . $this->post('mainId') . "' ");
        $infoMx = query(self::tableMx, " id = '" . $id . "' ");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('topic.table.edit_permission');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('topic.table.find_none_info');
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            if (empty($infoMx['id'])) {
                $field        = array_merge(
                    $field,
                    [
                        'id'      => $id,
                        'orderId' => $info['id'],
                        'state'   => '启用',
                        'stid'    => $this->control['stid'],
                        'time'    => $this->time,
                    ]
                );
                $json['warn'] = static::insert(array(
                    "table" => self::tableMx,
                    "field" => $field,
                ));
            } else {
                //更新
                $json['warn'] = update(array(
                    "table" => self::tableMx,
                    "field" => $field,
                    "where" => "id = '$infoMx[id]'",
                ));
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['title'], $id], L('topic.table.questions_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                if ($this->post('source')) {
                    //其他页面调用
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->post('source') . "&fun=detail&id=" . $id;
                } else {
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
                }
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 新增判断
     * @return string
     */
    public function addJudgment(): string
    {
        $mx      = query(self::tableMx, " id = '{$this->post('id')}'");
        $checked = [];
        $itemArr = [];
        if (!empty($mx['id'])) {
            $answer  = json_decode($mx['answer'], true);
            $itemArr = json_decode($mx['item'], true);
            foreach ($itemArr as $k => $val) {
                $checked[$k] = '';
                if ($k == $answer[0]) {
                    $checked[$k] = 'checked';
                }
            }
        }
        $itemText = "<div class='item_row'>" . text(array('name' => 'item[]', 'value' => $itemArr[0] ?? '对', 'class' => 'width200')) . "<label class='radioLabel'><input name='answer' value='0' type='radio' " . ($checked[0] ?? '') . ">&nbsp;" . L('topic.table.answer') . "</label></div>";
        $itemText .= "<div class='item_row'>" . text(array('name' => 'item[]', 'value' => $itemArr[1] ?? '错', 'class' => 'width200')) . "<label class='radioLabel'><input name='answer' value='1' type='radio' " . ($checked[1] ?? '') . ">&nbsp;" . L('topic.table.answer') . "</label></div>";
        //生成表单
        $data['html'] = $this->layerEdit(array("table"  => array(
            array(
                L('topic.table.questionsType') . "：" => L('topic.table.judge_choice'),
            ),
            array(
                L('topic.table.score') . "：" => text(array('name' => 'score', 'class' => 'text', 'value' => $mx['score']))
            ),
            array(
                must . L('topic.table.stem') . "：" => textarea(array('name' => 'title', 'class' => 'textarea', 'value' => $mx['title']))
            ),
            array(
                must . L('topic.table.option') . "：" => "<div id='item'>{$itemText}</div>"
            )
        ),
            'hidden' => hidden(array('name' => 'mainId', 'value' => $this->post('mainId'))) . hidden(array('name' => 'source', 'value' => $this->post('source'))) . hidden(array('name' => 'id', 'value' => $this->post('id'))),
        ));
        //返回
        return $this->layer(array(
            "title" => L('topic.table.judge_choice'),
            "height" => 350,
            "width" => 800,
            "html" => $data['html'],
            'button' => '<button class="button" onclick="subForm(\'' . self::page . 'AddJudgmentForm\',root+\'control/adIndex.html?cla=' . self::page . '&fun=addJudgmentEdit\')">' . L('staffProfiles.table.save') . '</button>'
        ));
    }


    /**
     * 判读编辑
     * @return bool|string
     */
    public function addJudgmentEdit()
    {
        $id         = $this->post('id') ?: self::getId();
        $field      = [
            'topicType' => '判断题',
            'title'     => $this->post('title'),
            'score'     => $this->post('score'),
            'item'      => $this->post('item') ? json_encode($this->post('item'), 320) : [],
            'answer'    => json_encode([$this->post('answer')], 320),
        ];
        $annotation = [
            'title'  => L('topic.table.stem'),
            'item'   => L('topic.table.option'),
            'answer' => L('topic.table.answer'),
        ];
        $rules      = [
            'title'  => 'required',
            'item'   => 'required',
            'answer' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        $info   = query(self::table, " id = '" . $this->post('mainId') . "' ");
        $infoMx = query(self::tableMx, " id = '" . $id . "' ");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('topic.table.edit_permission');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('topic.table.find_none_info');
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            if (empty($infoMx['id'])) {
                $field        = array_merge(
                    $field,
                    [
                        'id'      => $id,
                        'orderId' => $info['id'],
                        'state'   => '启用',
                        'stid'    => $this->control['stid'],
                        'time'    => $this->time,
                    ]
                );
                $json['warn'] = static::insert(array(
                    "table" => self::tableMx,
                    "field" => $field,
                ));
            } else {
                //更新
                $json['warn'] = update(array(
                    "table" => self::tableMx,
                    "field" => $field,
                    "where" => "id = '$infoMx[id]'",
                ));
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['title'], $id], L('topic.table.questions_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                if ($this->post('source')) {
                    //其他页面调用
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->post('source') . "&fun=detail&id=" . $id;
                } else {
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
                }
            }
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 新增多选
     * @return string
     */
    public function addMultiple(): string
    {
        $mx       = query(self::tableMx, " id = '{$this->post('id')}'");
        $itemText = '';
        if (!empty($mx['id'])) {
            $answer  = json_decode($mx['answer'], true);
            $itemArr = json_decode($mx['item'], true);
            foreach ($itemArr as $k => $val) {
                $checked = '';
                if (in_array($k, $answer)) {
                    $checked = 'checked';
                }
                if ($k == 0) {
                    $itemText .= "<div class='item_row'>" . text(array('name' => 'item[]', 'value' => $val, 'class' => 'width200')) . "<span onclick=\"addRowMultiple(this,'multiple')\" class='btn-borderless'>添加</span><label class='radioLabel'><input name='answer[]' value='$k' type='checkbox' {$checked}>&nbsp;" . L('topic.table.answer') . "</label></div>";
                } else {
                    $itemText .= "<div class='item_row'>" . text(array('name' => 'item[]', 'value' => $val, 'class' => 'width200')) . "<span class='btn-borderless' onclick='decRow(this)'>" . L('department.button.delete') . "</span><label class='radioLabel'><input name='answer[]' value='$k' type='checkbox' {$checked}>&nbsp;" . L('topic.table.answer') . "</label></div>";
                }
            }
        } else {
            for ($k = 0; $k < 4; $k++) {
                if ($k == 0) {
                    $itemText .= "<div class='item_row'>" . text(array('name' => 'item[]', 'class' => 'width200')) . "<span class='btn-borderless' onclick=\"addRowMultiple(this,'multiple')\">添加</span><label class='radioLabel'><input checked name='answer[]' value='$k' type='checkbox'>&nbsp;" . L('topic.table.answer') . "</label></div>";
                } else {
                    $itemText .= "<div class='item_row'>" . text(array('name' => 'item[]', 'class' => 'width200')) . "<span class='btn-borderless' onclick='decRow(this)'>" . L('department.button.delete') . "</span><label class='radioLabel'><input name='answer[]' value='$k' type='checkbox'>&nbsp;" . L('topic.table.answer') . "</label></div>";
                }
            }

        }
        //生成表单
        $data['html'] = $this->layerEdit(array("table"  => array(
            array(
                L('topic.table.questionsType') . "：" => L('topic.table.multiple_choice'),
            ),
            array(
                L('topic.table.score') . "：" => text(array('name' => 'score', 'class' => 'text', 'value' => $mx['score']))
            ),
            array(
                must . L('topic.table.stem') . "：" => textarea(array('name' => 'title', 'class' => 'textarea', 'value' => $mx['title']))
            ),
            array(
                must . L('topic.table.option') . "：" => "<div id='itemMultiple'>{$itemText}</div>"
            )
        ),
            'hidden' => hidden(array('name' => 'mainId', 'value' => $this->post('mainId'))) . hidden(array('name' => 'source', 'value' => $this->post('source'))) . hidden(array('name' => 'id', 'value' => $this->post('id'))),
        ));
        $data['html'] .= <<<eof
<script>
 //添加一行
         function addRowMultiple(e,type){
             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{type:type},function (res){
                 $("#itemMultiple").append(res.data);
                 reSetList();
             },'json');
         }
         function reSetList(){
             $("#itemMultiple [name='answer[]']").each(function (num){
                   $(this).val(num);
              })
         }
</script>

eof;

        //返回
        return $this->layer(array(
            "title" => L('topic.table.multiple_choice'),
            "height" => 450,
            "width" => 800,
            "html" => $data['html'],
            'button' => '<button class="button"  onclick="subForm(\'' . self::page . 'AddMultipleForm\',root+\'control/adIndex.html?cla=' . self::page . '&fun=addMultipleEdit\')">' . L('staffProfiles.table.save') . '</button>'
        ));
    }


    /**
     * 多选编辑
     * @return bool|string
     */
    public function addMultipleEdit()
    {
        $id         = $this->post('id') ?: self::getId();
        $field      = [
            'topicType' => '多选题',
            'title'     => $this->post('title'),
            'score'     => $this->post('score'),
            'item'      => $this->post('item') ? json_encode($this->post('item'), 320) : [],
            'answer'    => $this->post('answer') && is_array($this->post('answer')) ? json_encode($this->post('answer'), 320) : [],
        ];
        $annotation = [
            'title'  => L('topic.table.stem'),
            'item'   => L('topic.table.option'),
            'answer' => L('topic.table.answer'),
        ];
        $rules      = [
            'title'  => 'required',
            'item'   => 'required',
            'answer' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        $info   = query(self::table, " id = '" . $this->post('mainId') . "' ");
        $infoMx = query(self::tableMx, " id = '" . $id . "' ");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('topic.table.edit_permission');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('topic.table.find_none_info');
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            if (empty($infoMx['id'])) {
                $field        = array_merge(
                    $field,
                    [
                        'id'      => $id,
                        'orderId' => $info['id'],
                        'state'   => '启用',
                        'stid'    => $this->control['stid'],
                        'time'    => $this->time,
                    ]
                );
                $json['warn'] = static::insert(array(
                    "table" => self::tableMx,
                    "field" => $field,
                ));
            } else {
                //更新
                $json['warn'] = update(array(
                    "table" => self::tableMx,
                    "field" => $field,
                    "where" => "id = '$infoMx[id]'",
                ));
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['title'], $id], L('topic.table.questions_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                if ($this->post('source')) {
                    //其他页面调用
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->post('source') . "&fun=detail&id=" . $id;
                } else {
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
                }
            }
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 新增单选
     * @return string
     */
    public function addSingle(): string
    {
        $mx       = query(self::tableMx, " id = '{$this->post('id')}'");
        $itemText = '';
        if (!empty($mx['id'])) {
            $answer  = json_decode($mx['answer'], true);
            $itemArr = json_decode($mx['item'], true);
            foreach ($itemArr as $k => $val) {
                $checked = '';
                if ($k == $answer[0]) {
                    $checked = 'checked';
                }
                if ($k == 0) {
                    $itemText .= "<div class='item_row'>" . text(array('name' => 'item[]', 'value' => $val, 'class' => 'width200')) . "<span class='btn-borderless' onclick=\"addRow(this,'single')\">添加</span><label class='radioLabel'><input name='answer'  value='$k' type='radio' {$checked}>&nbsp;" . L('topic.table.answer') . "</label></div>";
                } else {
                    $itemText .= "<div class='item_row'>" . text(array('name' => 'item[]', 'value' => $val, 'class' => 'width200')) . "<span class='btn-borderless' onclick='decRow(this)'>" . L('department.button.delete') . "</span><label class='radioLabel'><input name='answer' value='$k' type='radio' {$checked}>&nbsp;" . L('topic.table.answer') . "</label></div>";
                }
            }
        } else {
            for ($k = 0; $k < 4; $k++) {
                if ($k == 0) {
                    $itemText .= "<div class='item_row'>" . text(array('name' => 'item[]', 'class' => 'width200')) . "<span class='btn-borderless'  onclick=\"addRow(this,'single')\">添加</span><label class='radioLabel'><input name='answer' value='$k' checked type='radio'>&nbsp;" . L('topic.table.answer') . "</label></div>";
                } else {
                    $itemText .= "<div class='item_row'>" . text(array('name' => 'item[]', 'class' => 'width200')) . "<span class='btn-borderless'   onclick='decRow(this)'>" . L('department.button.delete') . "</span><label class='radioLabel'><input name='answer' value='$k' type='radio'>&nbsp;" . L('topic.table.answer') . "</label></div>";
                }
            }

        }
        //生成表单
        $html = $this->layerEdit(array("table"  => array(
            array(
                L('topic.table.questionsType') . "：" => L('topic.table.single_choice'),
            ),
            array(
                L('topic.table.score') . "：" => text(array('name' => 'score', 'class' => 'text', 'value' => $mx['score']))
            ),
            array(
                must . L('topic.table.stem') . "：" => textarea(array('name' => 'title', 'class' => 'textarea', 'value' => $mx['title']))
            ),
            array(
                must . L('topic.table.option') . "：" => "<div id='item'>{$itemText}</div>"
            )
        ),
                                       'hidden' => hidden(array('name' => 'mainId', 'value' => $this->post('mainId'))) . hidden(array('name' => 'source', 'value' => $this->post('source'))) . hidden(array('name' => 'id', 'value' => $this->post('id'))),
        ));
        $html .= <<<eof
<script>
 //添加一行
         function addRow(e,type){
             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{type:type},function (res){
                 $(e).parents("#item").append(res.data);
                 reSetList();
             },'json');
         }
         function reSetList(){
             $("#item [name='answer']").each(function (num){
                   console.log(num);
                   $(this).val(num);
              })
         }
</script>

eof;
        return $this->layer(array(
            "title" => L('topic.table.single_choice'),
            "height" => 450,
            "width" => 800,
            "html" => $html,
            'button' => '<button class="button topic_bottom_button" onclick="subForm(\'' . self::page . 'AddSingleForm\',root+\'control/adIndex.html?cla=' . self::page . '&fun=addSingleEdit\')">' . L('staffProfiles.table.save') . '</button>'
        ));
        //返回
    }


    /**
     * 单选编辑
     * @return bool|string
     */
    public function addSingleEdit()
    {
        $id         = $this->post('id') ?: self::getId();
        $field      = [
            'topicType' => '单选题',
            'title'     => $this->post('title'),
            'score'     => $this->post('score'),
            'item'      => $this->post('item') ? json_encode($this->post('item'), 320) : [],
            'answer'    => json_encode([$this->post('answer')], 320),
        ];
        $annotation = [
            'title'  => L('topic.table.stem'),
            'item'   => L('topic.table.option'),
            'answer' => L('topic.table.answer'),
        ];
        $rules      = [
            'title'  => 'required',
            'item'   => 'required',
            'answer' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        $info   = query(self::table, " id = '" . $this->post('mainId') . "' ");
        $infoMx = query(self::tableMx, " id = '" . $id . "' ");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('topic.table.edit_permission');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('topic.table.find_none_info');
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            if (empty($infoMx['id'])) {
                $field        = array_merge(
                    $field,
                    [
                        'id'      => $id,
                        'orderId' => $info['id'],
                        'state'   => '启用',
                        'stid'    => $this->control['stid'],
                        'time'    => $this->time,
                    ]
                );
                $json['warn'] = static::insert(array(
                    "table" => self::tableMx,
                    "field" => $field,
                ));
            } else {
                //更新
                $json['warn'] = update(array(
                    "table" => self::tableMx,
                    "field" => $field,
                    "where" => "id = '$infoMx[id]'",
                ));
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['title'], $id], L('topic.table.questions_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                if ($this->post('source')) {
                    //其他页面调用
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->post('source') . "&fun=detail&id=" . $id;
                } else {
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
                }
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $type = $this->post('type');
        $html = '';
        switch ($type) {
            case 'single':
                //单选
                $html = "<div class='item_row'>" . text(array('name' => 'item[]', 'class' => 'width200')) . "<span class='btn-borderless' onclick='decRow(this)'>" . L('department.button.delete') . "</span><label class='radioLabel'><input name='answer' type='radio'>&nbsp;" . L('topic.table.answer') . "</label></div>";
                break;
            case 'multiple':
                $html = "<div class='item_row'>" . text(array('name' => 'item[]', 'class' => 'width200')) . "<span class='btn-borderless' onclick='decRow(this)'>" . L('department.button.delete') . "</span><label class='radioLabel'><input name='answer[]' type='checkbox'>&nbsp;" . L('topic.table.answer') . "</label></div>";
                break;
        }
        $json['data'] = $html;
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            case 'delMx':
                $act      = 'del';
                $msg      = L('topic.table.questions_del');
                $title    = self::page . 'DeleteMx';
                $function = 'deleteMx';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                break;
            default:
                $act      = 'del';
                $msg      = L('topic.table.topic_del');
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 启用/停用
     */
    public function stateSwitch()
    {
        $type     = $this->post('type');
        $classify = $this->post('classify');
        if ($classify == 'topic') {
            $formName = 'detailForm';
        } else {
            $formName = 'listForm';
        }
        $typeText = match ($type) {
            '启用' => L('topic.table.enable'),
            default => L('topic.table.unenable'),
        };
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                L('topic.table.tip') . "：" => L('topic.table.changeTip') . "：" . $typeText,
            ),
        ), 'hidden'                            => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'classify', 'value' => $classify))));
        //返回
        return $this->layer(array("title" => L('topic.table.stateChange'), "height" => 165, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit()
    {
        $state    = $this->post('type');
        $classify = $this->post('classify');
        if ($classify == 'topic') {
            $idArr = $this->post('tid') ? [$this->post('tid')] : $this->post('mxId');
        } else {
            $idArr = $this->post('listId');
        }
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('topic.table.edit_permission');
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = L('job.model.no_data_warn');
        } elseif (!in_array($state, ['启用', '停用'])) {
            $json['warn'] = L('topic.table.type_error');
        } elseif ($classify == 'topic') {
            $json['warn'] = update(array('table' => self::tableMx, 'field' => ['state' => $state], 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $operate = match ($state) {
                    '启用' => L('topic.table.enable'),
                    default => L('topic.table.unenable'),
                };
                $text    = str_replace(['{{staffName}}', '{{state}}'], [$this->control['name'], $operate], L('topic.table.stateChangeLog')) . implode("','", $idArr);
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            }
        } else {
            $json['warn'] = update(array('table' => self::table, 'field' => ['state' => $state], 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $operate = match ($state) {
                    '启用' => L('topic.table.enable'),
                    default => L('topic.table.unenable'),
                };
                $text    = str_replace(['{{staffName}}', '{{state}}'], [$this->control['name'], $operate], L('topic.table.stateChangeLog')) . implode("','", $idArr);
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('staffProfiles.tip.permission_del_warn');
        } elseif (empty($array)) {
            $json['warn'] = L('staffProfiles.tip.no_data_choose');
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '停用') {
                    $warn = L('topic.table.del_warn');
                } else {
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = L('job.other.delete_success');
                    $x++;
                }
                $text .= str_replace(['{{name}}', '{{id}}'], [$info['name'], $info['id']], L('topic.table.topic_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('topic.table.topic_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('topic.table.topic_del_warn'));
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除试题
     * @return bool|string
     */
    public function deleteMx()
    {
        $array = $this->post('mxId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('staffProfiles.tip.permission_del_warn');
        } elseif (empty($array)) {
            $json['warn'] = L('staffProfiles.tip.no_data_choose');
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $mx = query(self::tableMx, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::tableMx, "where" => " id = '$id' "));
                //返回
                $warn = L('job.other.delete_success');
                $x++;
                $text .= str_replace(['{{title}}', '{{id}}'], [$mx['title'], $mx['id']], L('topic.table.que_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('topic.table.que_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('topic.table.que_del_warn'));
            $json['warn']     = 2;
        }
        return json_encode($json, 320);
    }


    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify = ''): array
    {
        return match ($classify) {
            default => [
                [
                    'columnName' => '试题类型',
                    'aliasName'  => '试题类型',
                    'isMust'     => true,
                ],
                [
                    'columnName' => '题干',
                    'aliasName'  => '题干',
                    'isMust'     => true,
                ],
                [
                    'columnName' => '选项',
                    'aliasName'  => '选项',
                    'isMust'     => true,
                ],
                [
                    'columnName' => '正确答案',
                    'aliasName'  => '正确答案',
                    'isMust'     => true,
                ],
                [
                    'columnName' => '分值',
                    'aliasName'  => '分值',
                    'isMust'     => true,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify = ''): array
    {
        return match ($classify) {
            default => [
                [
                    'columnName' => '试题类型',
                    'aliasName'  => '试题类型',
                ],
                [
                    'columnName' => '题干',
                    'aliasName'  => '题干',
                ],
                [
                    'columnName' => '选项',
                    'aliasName'  => '选项',
                ],
                [
                    'columnName' => '正确答案',
                    'aliasName'  => '正确答案',
                ],
                [
                    'columnName' => '分值',
                    'aliasName'  => '分值',
                ],
            ]
        };
    }

}
